package com.honda.controller.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.honda.model.User;
import com.honda.util.JsonUtils;

public class HttpClient {

	protected final static Logger log = LoggerFactory
			.getLogger(HttpClient.class);
	private final static CloseableHttpClient httpclient = HttpClients
			.createDefault();

	public static void main(String[] args) {

	//	String url = "http://localhost:8080/restful/http/getByUserId";
		String url = "http://172.20.10.2:7800/rest/test";

		// get请求
		
		  String doGet = HttpClient.doGet(url); 
		  System.out.println(doGet);
		   

		// post请求
		/*List<User> users = new ArrayList<User>();
		User user = null;
		for (int i = 0; i < 3; i++) {
			user = new User();
			user.setId("ii" + i);
			user.setPassword("password" + i);
			user.setUsername("username" + i);
			users.add(user);
		}

		String url1 = "http://localhost:8080/restful/http/save";
		String jsonParam = JsonUtils.objectToJson(users);

		String doPost = HttpClient.doPost(url1, jsonParam);
		System.out.println(doPost)*/;
	}

	/**
	 * 
	 * @Title: doGet
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param url
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	public static String doGet(String url) {

		CloseableHttpResponse response = null;
		StringBuffer reponse = new StringBuffer();
		try {
			HttpGet getRequest = new HttpGet(url);
			getRequest.addHeader("accept", "application/json");
			// ESB所需数据begin
			getRequest.addHeader("RequestID", "1111");
			getRequest.addHeader("SourceSystem", "ESB");
			getRequest.addHeader("TargetSystem", "Rest");
			getRequest.addHeader("ServiceName", "WS_rest_test");
			// end
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(20000)
					.setConnectionRequestTimeout(15000).setSocketTimeout(20000)
					.build();

			getRequest.setConfig(requestConfig);

			response = httpclient.execute(getRequest);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatusLine().getStatusCode());
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(response.getEntity().getContent())));

			String output = "";
			while ((output = br.readLine()) != null) {
				reponse.append(output);
			}
			Header headers[] = response.getAllHeaders();   
			int i = 0;    
		    
	        while (i < headers.length) { 
	        	System.out.println(headers[i].getName() + ":  " + headers[i].getValue());    
	            
	        	if(headers[i].getName().equals("EsbDesc")){
	        		
	        		byte[] decode = Base64.getDecoder().decode(headers[i].getValue().getBytes());
	        		System.out.println(new String(decode, "UTF-8"));
	        	}
                i++;  
	        }
	        
			return reponse.toString();
		} catch (Exception e) {
			log.error("" + e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	/***
	 * 
	 * @Title: doPost
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param url
	 * @param: @param jsonParam
	 * @param: @return
	 * @return: String
	 * @throws
	 */
	public static String doPost(String url, String jsonParam) {
		CloseableHttpResponse response = null;
		StringBuffer reponse = new StringBuffer();
		try {
			HttpPost postRequest = new HttpPost(url);

			if (jsonParam != null) {
				StringEntity input = new StringEntity(jsonParam,
						ContentType.create("application/json", "utf-8"));
				postRequest.setEntity(input);
			}
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(20000)
					.setConnectionRequestTimeout(15000).setSocketTimeout(20000)
					.build();
			postRequest.setConfig(requestConfig);

			// ESB所需数据 begin
			postRequest.setHeader("RequestID", "1111");
			postRequest.setHeader("SourceSystem", "OSM");
			postRequest.setHeader("TargetSystem", "ESB");
			postRequest.setHeader("ServiceName", "xxxxxx");
			// end
			response = httpclient.execute(postRequest);

			if (response.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatusLine().getStatusCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(response.getEntity().getContent()), "UTF-8"));

			String output = "";
			while ((output = br.readLine()) != null) {
				reponse.append(output);
			}

			return reponse.toString();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("" + e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
